<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header flex-sb">
          <span>{{ route.query.id ? "编辑商品" : "添加商品" }}</span>
          <div>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit()">保存</el-button>
          </div>
        </div>
      </template>
      <el-form :model="form" :rules="rules" label-width="auto" ref="ruleFormRef">
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" />
        </el-form-item>
        <el-form-item label="商品编号" prop="goodsNo">
          <el-input v-model="form.goodsNo" />
        </el-form-item>
        <el-form-item label="商品标题" prop="goodsTitle">
          <el-input v-model="form.goodsTitle" />
        </el-form-item>
        <el-card
          class="specification-card"
          shadow="never"
          v-for="(item, index) in form.goodsSpecificationList"
          :key="index"
        >
          <template #header>
            <div class="form-card-header">
              <span>商品规格{{ index + 1 }}</span>
              <div>
                <el-button type="primary" plain @click="handleAddSpec()" v-if="index == 0">
                  添加规格
                </el-button>
                <el-button type="danger" plain @click="handleDelSpec(index)" v-else>
                  删除规格
                </el-button>
              </div>
            </div>
          </template>
          <el-form-item label="规格名称">
            <el-input v-model="item.optionName" />
          </el-form-item>
          <el-form-item label="规格编码">
            <el-input v-model="item.goodsBarcode" />
          </el-form-item>
          <el-form-item label="标价">
            <el-input-number v-model="item.tagPrice" />
          </el-form-item>
          <el-form-item label="促销价">
            <el-input-number v-model="item.promotionalPrice" />
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="item.stockNum" />
          </el-form-item>
          <el-form-item label="规格图片">
            <el-upload
              v-model:file-list="item.fileList"
              list-type="picture-card"
              :before-upload="handleBeforeUpload"
              :http-request="handleUpload"
              :on-success="(v) => handleSuccess(v, item, index)"
              :on-error="handleError"
              :on-remove="(v) => handleRemove(v, item, index)"
              :accept="'jpg,png,jpeg'"
              :limit="1"
            >
              <el-icon v-if="item.fileList.length == 0"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-card>
        <el-form-item label="店铺" prop="storeId">
          <el-select v-model="form.storeId" placeholder="请选择店铺">
            <el-option
              v-for="item in storeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="促销价格" prop="promotionalPrice">
          <el-input-number v-model="form.promotionalPrice" :min="1" :max="999999" />
          <!-- <el-input v-model="form.promotionalPrice" /> -->
        </el-form-item>
        <el-form-item label="商品标价" prop="tagPrice">
          <el-input-number v-model="form.tagPrice" :min="1" :max="999999" />
        </el-form-item>
        <el-form-item label="商品描述" prop="goodsDescription">
          <el-input
            v-model="form.goodsDescription"
            :autosize="{ minRows: 2, maxRows: 8 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="商品详情" prop="goodsDetails">
          <el-input
            v-model="form.goodsDetails"
            :autosize="{ minRows: 2, maxRows: 8 }"
            type="textarea"
          />
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <!-- <div class="dialog-footer">
    <el-button @click="handleClose">取消</el-button>
    <el-button type="primary" @click="handleSubmit()">确定</el-button>
  </div> -->
</template>

<script lang="ts" setup>
import Vue, { reactive, ref, onMounted } from "vue";
//import PhotoModal from "@/views/photoModal";
import type { FormInstance, FormRules } from "element-plus";
import CategoryAPI from "@/api/system/category.api";
import StoreAPI from "@/api/system/store.api";
import GoodsAPI from "@/api/system/goods.api";
import FileAPI, { FileInfo } from "@/api/file.api";

import { usePermissionStore, useTagsViewStore, useSettingsStore, useAppStore } from "@/store";
import { url } from "inspector";
import {
  UploadRawFile,
  UploadUserFile,
  UploadFile,
  UploadProgressEvent,
  UploadRequestOptions,
} from "element-plus";
import { loadEnv } from "vite";

const route = useRoute();
const router = useRouter();

const tagsViewStore = useTagsViewStore();

// 组件接收参数
defineOptions({
  name: "User",
  inheritAttrs: false,
});
interface SpecificationItem {
  optionName: string;
  headerImgPath: string;
  goodsBarcode: string;
  tagPrice: number;
  promotionalPrice: number;
  stockNum: number;
}
interface RuleForm {
  goodsName: string;
  goodsNo: string;
  goodsTitle: string;
  goodsDescription: string;
  goodsDetails: string;
  promotionalPrice: number;
  tagPrice: number;
  goodsSpecificationList: SpecificationItem[];
  categoryId: string;
  storeId: string;
}
const emit = defineEmits(["success"]);
const env = import.meta.env;
const storeOptions = ref<OptionType[]>();
const categoryOptions = ref<OptionType[]>();

const ruleFormRef = ref<FormInstance>();
const visible = ref(false);
let form = reactive({
  goodsName: "",
  goodsNo: "",
  goodsTitle: "",
  goodsDescription: "",
  goodsDetails: "",
  promotionalPrice: 0,
  tagPrice: 0,
  goodsSpecificationList: [
    {
      optionName: "",
      headerImgPath: "",
      goodsBarcode: "",
      tagPrice: 0,
      promotionalPrice: 0,
      stockNum: 0,
      fileList: [],
    },
  ],
  categoryId: "",
  storeId: "",
});
const rules = reactive<FormRules<RuleForm>>({
  goodsName: [{ required: true, message: "输入商品名称", trigger: "blur" }],
});

function handleAddSpec() {
  form.goodsSpecificationList.push({
    optionName: "",
    headerImgPath: "",
    goodsBarcode: "",
    tagPrice: 0,
    promotionalPrice: 0,
    stockNum: 0,
    fileList: [],
  });
}

function handleDelSpec(index: number) {
  form.goodsSpecificationList.splice(index, 1);
}
function getList() {
  StoreAPI.getList({
    page: 1,
    pageSize: 999,
  }).then((data) => {
    console.log(data);
    storeOptions.value = data.map((item) => ({
      label: item.storeName,
      value: item.id,
    }));
  });
  CategoryAPI.getList({
    page: 1,
    pageSize: 999,
  }).then((data) => {
    console.log(data);
    categoryOptions.value = data.map((item) => ({
      label: item.categoryName,
      value: item.id,
    }));
  });
}

async function initData() {
  if (route.query.id) {
    const data = await GoodsAPI.detailInfo({ id: route.query.id });
    console.log(data);
    form.goodsName = data.goodsName;
    form.goodsNo = data.goodsNo;
    form.goodsTitle = data.goodsTitle;
    form.goodsDescription = data.goodsDescription;
    form.goodsDetails = data.goodsDetails;
    form.promotionalPrice = data.promotionalPrice;
    form.tagPrice = data.tagPrice;
    form.categoryId = data.categoryId;
    form.storeId = data.storeId;
    form.goodsSpecificationList = data.goodsSpecificationList.map((item, index) => {
      return {
        optionName: item.optionName,
        headerImgPath: item.headerImgPath,
        goodsBarcode: item.goodsBarcode,
        tagPrice: item.tagPrice,
        promotionalPrice: item.promotionalPrice,
        stockNum: item.stockNum,
        fileList: [
          {
            name: `规格图片${index + 1}`,
            url: `${env.VITE_APP_API_URL}/${item.headerImgPath}`,
          },
        ],
      };
    });
  }
}

function handleClose() {
  handleReset();
  tagsViewStore.closeCurrentView();
  router.push({ name: "GoodsIndex" });
}

function handleSubmit() {
  (ruleFormRef.value as FormInstance).validate(async (valid) => {
    if (valid) {
      if (route.query.id) {
        let params = {
          ...form,
          id: route.query.id,
          goodsSpecificationList: form.goodsSpecificationList.map((item: any) => {
            return {
              optionName: item.optionName,
              headerImgPath: item.headerImgPath,
              goodsBarcode: item.goodsBarcode,
              tagPrice: item.tagPrice,
              promotionalPrice: item.promotionalPrice,
              stockNum: item.stockNum,
            };
          }),
        };
        const data = await GoodsAPI.update(params);
        if (data == "1") {
          ElMessage.success("操作成功");
          tagsViewStore.closeCurrentView();
          router.push({ name: "GoodsIndex" });
        } else {
          ElMessage.error("操作失败");
        }
      } else {
        let params = {
          ...form,
          goodsSpecificationList: form.goodsSpecificationList.map((item: any) => {
            return {
              optionName: item.optionName,
              headerImgPath: item.headerImgPath,
              goodsBarcode: item.goodsBarcode,
              tagPrice: item.tagPrice,
              promotionalPrice: item.promotionalPrice,
              stockNum: item.stockNum,
            };
          }),
        };
        const data = await GoodsAPI.add(params);
        console.log(data);
        if (data == "1") {
          ElMessage.success("操作成功");
          tagsViewStore.closeCurrentView();
          router.push({ name: "GoodsIndex" });
        } else {
          ElMessage.error("操作失败");
        }
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
}

/*
 * 上传文件
 */
function handleUpload(options: UploadRequestOptions) {
  return new Promise((resolve, reject) => {
    const file = options.file;
    const formData = new FormData();
    formData.append("GoodsPic", file);
    FileAPI.addSpecImage(formData)
      .then((data) => {
        resolve(data);
      })
      .catch((error) => {
        reject(error);
      });
  });
}
/**
 * 上传前校验
 */
function handleBeforeUpload(file: UploadRawFile) {
  // 限制文件大小
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.warning("上传图片不能大于" + 2 + "M");
    return false;
  }
  return true;
}

/**
 * 上传成功
 */
const handleSuccess = (fileInfo: FileInfo, row: any, index: nuber) => {
  ElMessage.success("上传成功");
  console.log("handleSuccess", fileInfo);
  console.log("row", row);
  console.log("index", index);

  // const env = loadEnv( process.cwd());
  // modelValue.value = [...modelValue.value, { name: fileInfo.name, url: fileInfo.url } as FileInfo];
  // emit("upload-success", fileInfo);
  row.fileList = [
    {
      name: `图片${index + 1}`,
      url: `${env.VITE_APP_API_URL}/${fileInfo}`,
      status: "success",
      uid: getUid(),
    },
  ];
  row.headerImgPath = fileInfo;
};

const handleRemove = (fileInfo: any, row: any, index) => {
  row.fileList = [];
  row.headerImgPath = "";
};

/** 获取一个不重复的id */
function getUid(): number {
  // 时间戳左移13位（相当于乘以8192） + 4位随机数
  return (Date.now() << 13) | Math.floor(Math.random() * 8192);
}
/**
 * 上传失败
 */
const handleError = (_error: any) => {
  console.error(_error);
  ElMessage.error("上传失败");
};
function handleReset() {
  (ruleFormRef.value as FormInstance).resetFields();
}

onMounted(() => {
  getList();
  initData();
});
</script>

<style>
.form-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.specification-card {
  margin-bottom: 20px;
}
</style>
